'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');

const OSS = require('ali-oss');
const client = new OSS({
    region: 'oss-cn-beijing',
    accessKeyId: 'LTAI5tLyHjYhKH8YnBTttpQK',
    accessKeySecret: '8UDAf4hsm0btmvpFmzKdJmnUiT7UDR',
    bucket: 'uploadimg-lwj',
});

class uploadController extends Controller {
    async index() {
        const { ctx } = this;
        ctx.body = ' hi egg';
    }

    // 图片上传
    async getImg() {
        const { ctx, app } = this;
        // 获取到authorization
        const { authorization } = ctx.request.header

        // 获取文件信息
        const file = ctx.request.files[0]

        const data = await client.put(file.filename, file.filepath)

        try {
            // 解密token
            const id = jwt.verify(authorization, '1907A')
            console.log(id);

            await app.mysql.update('houselist', { id, img: data.url })

            ctx.body = {
                code: 1,
                msg: '上传成功',
                data,
            }

        } catch (error) {
            ctx.body = {
                code: 0,
                msg: '上传失败'
            }
        }


    }


    // 视频上传
    async getVideo() {
        const { ctx, app } = this;
        // 获取到authorization
        const { authorization } = ctx.request.header

        // 获取文件信息
        const file = ctx.request.files[0]

        const data = await client.put(file.filename, file.filepath)

        try {
            // 解密token
            const id = jwt.verify(authorization, '1907A')
            console.log(id);

            await app.mysql.update('houselist', { id, video: data.url })

            ctx.body = {
                code: 1,
                msg: '上传成功',
                data,
            }

        } catch (error) {
            ctx.body = {
                code: 0,
                msg: '上传失败'
            }
        }


    }


}

module.exports = uploadController;
